/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var when = require("mlib/util/when");
var ajax = require("mlib/io/ajax");
var virtualLink = require("mlib/util/virtualLink");
var follow = require("../public/js/follow");
var round = require("../plugin/util/round");
var error = require("../public/js/error");
var date = require("../plugin/util/date");
var parseUrl = require("../plugin/url/parse-url");
var closest = require("mlib/dom/closest");

var Confirm = require("../layer/weuiconfirm");
var Alert = require("../layer/weuialert");
var touch = require("mlib/evt/touch");

var render = require("./single.ejs"); // 页面总模板

module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
    var detaildata = null;
    
    var statusCode = {
        "NORMAL":"use",
        "FREEZE":"invalid",
        "CONSUMED":"used",
        "EXPIRE":"invalid",
        "GIFTING":"donationing",
        "GIFT_SUCC":"donationed",
        "GIFT_TIMEOUT":"invalid",
        "UNAVAILABLE":"invalid"
    };
    var invalidCode = {
        "NORMAL":"未使用",
        "FREEZE":"已失效",
        "CONSUMED":"已使用",
        "EXPIRE":"已过期",
        "GIFTING":"转赠中",
        "GIFT_SUCC":"已转赠",
        "DELETE":"已删除",
        "GIFT_TIMEOUT":"券超时",
        "UNAVAILABLE":"无效券"
    };

    //-------------事件响应声明---------------
    var evtFuncs = {
        getVoucher:function(evt){
            follow();
        },
    	soonReceive:function(evt){
            var node = closest(evt.target,"button.soon-receive"),reqUrl = node.dataset.url;
					if(that.isLock()) {
						return;
					}
					that.lock();
                ajax({
                    url: reqUrl,
                    data:{"codeId":parseUrl(reqUrl).codeId},
                    method:'post',
                    onSuccess: function(result) {
						that.unLock();                        
                         if(result.status==1){
                               location.href= result.data.detailRouter;
                         }else{
                            Alert(result.msg);
                         }
                    },
                    onError: function(xmlHttp) {
						that.unLock();
                    }
                });
    	},
        joinWechat:function(evt){            
            var node = closest(evt.target,"button.join-wechat"),reqUrl = node.dataset.url;
                if(node.classList.contains("disabled")){
                    return;
                }
                ajax({
                    url: reqUrl,
                    data:{},
                    method:'post',
                    onSuccess: function(result) {   
                        wechat('off').init();
                        node.classList.add("disabled");           
                        if(result.status == 1){
                            location.href = result.data.syncRouter;
                        }else{
                        	Alert("sorry,放入微信卡包出错啦~");
                        }                        
                    },
                    onError: function(xmlHttp) {

                    }
                });
        },
            getTicket:function(evt){
                    if(this.classList.contains("disabled")){
                        return ;
                    }
                    this.classList.add("disabled");
                    var reqUrl = this.dataset.url;
                    var m_cardid = parseUrl(reqUrl).codeId;
					if(that.isLock()) {
						return;
					}
					that.lock();
                    ajax({
                        url:reqUrl,
                        data:{"codeId":m_cardid},
                        method: "post",
                        onSuccess: function(result) {
							that.unLock();
                           if(result.status>0){                               
                                    location.href=result.data.detailRouter;                            
                                                           
                           }else{
                                Alert(result.msg);
                           }
                                            
                        },
                        onError: function(xmlHttp) {
                           that.unLock();
                        }
                    });
            },
        giveFriend:function(evt){
            Confirm({"content":"发起转赠后，该券将不可使用，出现在已失效分类下，该券24小时内若无人领取，将重新可用","okFn":function(){
                var node = nodeList.donation,reqUrl = node.dataset.url;
					if(that.isLock()) {
						return;
					}
					that.lock();
                ajax({
                    url: reqUrl,
                    data:{},
                    method:'post',
                    onSuccess: function(result) {
                        that.unLock();
                        if(result.status==1){
                            nodeList.transfer.style.display = "block";                        
                            wechat('open',{
                                "title":"您的朋友赠送您一张优惠券",
                                "link":location.origin+result.data.giveRouter,
                                "imgUrl":data.imgDomain +"/weixin/couponLog.jpg",
                                "desc":detaildata.title
                            }).init();
                        }else{
                            Alert(result.msg);
                        }
                    },
                    onError: function(xmlHttp) {
						that.unLock();
                    }
                });
                this.hide();
            },"okText":"发起转赠"});

        }
	}

    //-------------子模块实例化---------------
    var initMod = function() { 
		virtualLink(function(evt){
			location.href = evt.target.getAttribute("data-href");
		});
		//wechat('off').init();
            custFuncs.getMpinfo().then(custFuncs.getDetail).otherwise(function(msg) { 
                console.log("报错信息：" + msg);
            });
             // custFuncs.getDetail();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
                touch.on(document.body, 'tap', "button.join-wechat", evtFuncs.joinWechat);
                touch.on(document.body, 'tap', "button.soon-receive", evtFuncs.soonReceive);
                touch.on(document.body, 'tap', ".donation", evtFuncs.giveFriend);
                touch.on(document.body, 'tap', ".followme", evtFuncs.getVoucher);
                touch.on(document.body, 'tap', "#getTicket", evtFuncs.getTicket);

	}

    //-------------自定义函数----------------
    var custFuncs = {
		
            getMpinfo:function (result){    
                var defer = when.defer(); 
                ajax({ 
                    url: "/index.php?r=CouponApi/data/wechat",
                    onSuccess: function(res) {
                        defer.resolve(res.data);
                    },
                    onError: function(xmlHttp) {
                         that.unLock();
                    }
                });
                return defer.promise;
                
            },
     		getDetail:function(params){
					ajax({
						url: data.requestAPIUrl,
						onSuccess: function(result) {
                            if(result.status==0){
                                error('error'); 
                                return;
                            }
                            if(result.data.cardStatus<1 || result.data.cardStatus>2){
                                error('error'); 
                                return;
                            }
                            result.data.isSelf = data.isSelf;
                            result.data.statusCode = statusCode;
                            result.data.invalidCode = invalidCode;
                            result.data.imgDomain = params.imgDomain;
                            result.data.logoUrl = params.logoUrl;
                            result.data.mpName = params.publicname;
							document.body.insertAdjacentHTML('AfterBegin', render(result.data));
                            detaildata=result.data;
                            // 找到所有带有node-name的节点
                            nodeList = parseModule(node);
							if(nodeList.publicName){
								nodeList.publicName.innerHTML = params.publicname;
							} 
                          //  touch.on(nodeList.viewDetail, 'tap', evtFuncs.viewDetail);
                            
                          //  nodeList.header.style.height = Math.ceil(nodeList.header.clientWidth*0.5548172757475083) + "px";
                           if(detaildata.canShared==1){
                                wechat('open',{
                                    "title":"您的朋友分享给您一张优惠券",
                                    "link":window.location.origin + detaildata.code.shareRouter,
                                    "imgUrl":data.imgDomain +"/weixin/couponLog.jpg",
                                    "desc":detaildata.title,
                                    "success":function (res) {
                                        ajax({
                                            url:decodeURIComponent(detaildata.code.shareSuccessRouter),
                                            onSuccess: function(result) {

                                            },
                                            onError: function(xmlHttp) {

                                            }
                                        });
                                 
                                    }
                                }).init();
                           }
						},
						onError: function(xmlHttp) {

						}
					});
    		}
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};